package com.just.fun.arithmetic;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class TreeNodeTest {

    public static void main(String[] args) {
        TreeNode treeNode = buildTreeNode();
        ArrayList<ArrayList<Integer>> print = print(treeNode);
        System.out.println(print);
    }

    /**
     * 按层打印二叉树
     * [1],[2,3],[4,5,6,7]
     * <p>
     * 就是二叉树的层序遍历，用队列来实现。我们需要两个变量，一个start记录当前层已经打印的节点个数，一个end记录前当层所有的节点个数，
     * 当 start == end 时，表时当前层遍历完了，就可以开始下一层遍历。
     * 利用队列先进先出的特性
     *
     * @param pRoot
     * @return
     */
    public static ArrayList<ArrayList<Integer>> print(TreeNode pRoot) {
        if (pRoot == null) {
            return null;
        }
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        ArrayList<Integer> temp = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        int start = 0, end = 1;
        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            temp.add(poll.val);
            start++;
            if (poll.left != null) {
                queue.add(poll.left);
            }
            if (poll.right != null) {
                queue.add(poll.right);
            }
            if (start == end) {
                start = 0;
                end = queue.size();
                result.add(temp);
                temp = new ArrayList<>();
            }
        }
        return result;

    }

    /**
     * 创建一个二叉树，1-7
     *
     * @return
     */
    public static TreeNode buildTreeNode() {
        TreeNode n1 = new TreeNode(1);
        TreeNode n2 = new TreeNode(2);
        TreeNode n3 = new TreeNode(3);
        TreeNode n4 = new TreeNode(4);
        TreeNode n5 = new TreeNode(5);
        TreeNode n6 = new TreeNode(6);
        TreeNode n7 = new TreeNode(7);

        n1.left = n2;
        n1.right = n3;
        n2.left = n4;
        n2.right = n5;
        n3.left = n6;
        n3.right = n7;
        return n1;
    }
}
